package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

//开启事务
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        /**
         * 保存菜品数据
         * 1.创建dish对象
         * 2.将dishDTO对象属性复制到dish对象中
         * 3.将dish插入到表中（需要插入以后的返回值id）
         * 4.从dishDTO中获取flavor对象，遍历进行插入
         *
         */
        Dish dish =new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        dishMapper.insert(dish);

        dishDTO.getFlavors().forEach(dishFlavor -> {
            //设置关联的菜品id
            dishFlavor.setDishId(dish.getId());
        });

        dishFlavorMapper.insertBatch( dishDTO.getFlavors());




    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //使用PageHelper插件实现分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page page=dishMapper.page(dishPageQueryDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Transactional
    @Override
    public void delete(Long[] ids) {
        /**
         * 1.遍历数组，获取id
         * 2.判断菜品状态，如果状态是启售状态，则不能删除
         * 3.如果菜品被套餐关联，则不能删除
         * 4.如果菜品与口味关联，则删除口味数据
         */
        for (Long id : ids) {
            Dish dish=dishMapper.findById(id);
            if (dish.getStatus()== StatusConstant.ENABLE){
                //启售状态
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            List<SetmealDish> setmealDishes=setmealDishMapper.getByDishId(id);
            if (setmealDishes!=null&&setmealDishes.size()>0){
                //被套餐关联
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
            //删除菜品数据
            dishMapper.deleteById(id);

            dishFlavorMapper.deleteByDishId(id);
        }
    }

    @Override
    public DishVO getByIdWithFlavors(Long id) {
        /**
         * 1.去dish表中查询菜品数据
         * 2.去dish_flavor表中查询口味数据
         * 3.将两个数据封装到DishVO中并返回
         */

        Dish dish = dishMapper.findById(id);
        List<DishFlavor> dishFlavors=dishFlavorMapper.findByDishId(id);
        DishVO dishVO=new DishVO();
        //拷贝菜品数据
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;

    }

    @Transactional
    @Override
    public void updateWithFlavors(DishDTO dishDTO) {
        /**
         * 1.修改dish表（把dishDTO-->dish）
         * 2.删除dish_flavor表
         * 3.批量插入dish_flavor表
         */
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors.forEach( dishFlavor-> dishFlavor.setDishId(dishDTO.getId()));


        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 启售停售
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    @Override
    public List<DishVO> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }
}
